package com.yangwp.doutu.controller;

import com.yangwp.doutu.Utils.ConvertUtil;
import com.yangwp.doutu.Utils.FileUtils;
import com.yangwp.doutu.model.Image;
import com.yangwp.doutu.service.CommentService;
import com.yangwp.doutu.service.ImageService;
import com.yangwp.doutu.service.LikeService;
import org.apache.cxf.helpers.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/image")
public class ImageController {

    @Autowired
    private ImageService imageService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeService likeService;

    @RequestMapping("/getImageRandom")
    @ResponseBody
    public void getImage(HttpServletResponse response){
        response.setContentType("image/jpeg");

        Image image = imageService.getImageRandom();
        File file = new File(FileUtils.IMAGE_PATH, image.getImagePath() + "/3ac998ca12ee9e423a2a3dce1efd9c14" );
        if(file.exists()){
            try {
                Integer commentNum = commentService.getCommentNum(image.getMd5());
                Integer likeNum = likeService.getLikeNum(image.getMd5());
                OutputStream out = response.getOutputStream();
                out.write(ConvertUtil.intToByteArray(commentNum));
                out.write(ConvertUtil.intToByteArray(likeNum));
                out.write(image.getMd5().getBytes());
                InputStream in = new FileInputStream(file);
                IOUtils.copy(in, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
